package com.fjec.devops.controller;

import com.fjec.common.Const;
import com.fjec.common.jxls.DataFour;
import com.fjec.common.redis.RedisGenIdHelper;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.util.SequenceIdGenerator;
import com.fjec.devops.feign.MarketClient;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/")
public class DemoController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private SequenceIdGenerator idGenerator;

    @GetMapping("/gen/id/test2")
    public JsonResult test2() {
        Map<String, Object> map = new HashMap<>();
        map.put("seed", RedisGenIdHelper.getSeed());
        map.put("id", idGenerator.nextId());
        return JsonResult.success()
                .data(RedisGenIdHelper.getSeed())
                .other(map)
                .build();
    }

    @GetMapping("/redis/test0")
    public String test0() {
        SimpleDateFormat yyMMdd = new SimpleDateFormat("yyMMdd");
        String firstToSixthNumber = yyMMdd.format(new Date());//第四到九位：年月日用于生产批号判断
        if (redisTemplate.hasKey(firstToSixthNumber)) {
            redisTemplate.opsForValue().increment(firstToSixthNumber, 1);
            redisTemplate.expire(firstToSixthNumber, 1000 * 60, TimeUnit.MILLISECONDS);//设置一分钟过期
        } else {
            redisTemplate.opsForValue().set(firstToSixthNumber, 0);
        }
        String s = redisTemplate.opsForValue().get(firstToSixthNumber).toString();
        String tenthToFifteenthNumber = String.format("%06d", Integer.parseInt(s));//第十到十五位数字：当天生产的盒子数量
        return firstToSixthNumber + tenthToFifteenthNumber;
    }


    @GetMapping("/redis/test1")
    public String test1() {
        ExecutorService es = Executors.newFixedThreadPool(30);
        final String key = "fjec:test:101";
        for (int i = 0; i < 100; i++) {
            es.execute(() -> {
                redisTemplate.watch(key);
                redisTemplate.multi();
                if (redisTemplate.hasKey(key)) {
                    redisTemplate.opsForValue().increment(key, 1);
//            redisTemplate.expire(key, 1000*60, TimeUnit.MILLISECONDS);//设置一分钟过期
                } else {
                    redisTemplate.opsForValue().set(key, 0);
                }
                System.out.println(redisTemplate.opsForValue().get(key));
                redisTemplate.exec();
            });
        }
        return "ok";
    }

    private Integer plus(String key) {
        if (redisTemplate.hasKey(key)) {
            redisTemplate.opsForValue().increment(key, 1);
//            redisTemplate.expire(key, 1000*60, TimeUnit.MILLISECONDS);//设置一分钟过期
        } else {
            redisTemplate.opsForValue().set(key, 0);
        }
        return (Integer) redisTemplate.opsForValue().get(key);
    }

    @GetMapping("/redis/cache/test")
    public JsonResult redisTest(String phone) {
        String key = Const.FJEC_SMS_VERIFY_CODE_KEY + phone;
        Object obj = redisTemplate.opsForValue().get(key);
        return JsonResult.success()
                .data(obj)
                .build();
    }

    @Resource
    private MarketClient marketClient;

    @GetMapping("/n/demo/market/client")
    public JsonResult statTest() {
        List<Map<String, Object>> resultList = marketClient.statAllPersonalData(3);
        return JsonResult.success()
                .data(resultList)
                .build();
    }

    @GetMapping("/y/excel/test1")
    public void test1(HttpServletResponse res) {
        String contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        res.setContentType(contentType);
        res.addHeader("content-disposition", "inline;filename=test.xlsx");
        res.addHeader("filename", "test.xlsx");
        res.addHeader("Access-Control-Expose-Headers", "filename");
        List<DataFour> dataList = generateData4();
//        String src = "E:\\data\\desktop\\客户协议图片\\银盛配置模板\\template_4.xlsx";
        try (InputStream is = this.getClass().getResourceAsStream("/excelTemplate/template_4.xlsx")) {
            try (OutputStream os = res.getOutputStream()) {
                Context context = new Context();
                context.putVar("dataList", dataList);
                JxlsHelper.getInstance().processTemplate(is, os, context);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static List<DataFour> generateData4() {
        List<DataFour> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(new DataFour(
                    "code_" + i,
                    "legal_name_" + i,
                    "legal_cert_no_" + i,
                    "phone_" + i,
                    "address_" + i,
                    "licence_number_" + i
            ));
        }
        return list;
    }
}
